package com.study.demo01.controller;

import com.study.demo01.dto.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "LoginServlet", urlPatterns = "/login.do")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        //先从缓存中拿出users
        ServletContext sc = request.getServletContext();
        List<User> users = (List<User>) sc.getAttribute("users");
       for (User u : users) {
           if(u.getUserName().equals(username)&&u.getPwd().equals(pwd)){
               //跳转到index.jsp

               HttpSession session = request.getSession();
               session.setAttribute("session_user",u);
               request.getRequestDispatcher("index.jsp").forward(request,response);
           }
        }
       //提示用户名密码不正确
        request.setAttribute("tip","用户名密码不正确!");
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
